package fu.capstone.hanoicityguide.dataaccess.transport;

import java.util.ArrayList;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import fu.capstone.hanoicityguide.business.model.Transportation;
import fu.capstone.hanoicityguide.dataaccess.base.BaseDAOImpl;
import fu.capstone.hanoicityguide.dataaccess.base.DatabaseHelper;

public class TransportDAOImp extends BaseDAOImpl implements TransportDAO {

	private SQLiteDatabase database;
	private DatabaseHelper dbHelper;
	private Context context;

	public TransportDAOImp(Context ctx) {
		super(ctx);
		this.context = ctx;
	}

	@Override
	public ArrayList<Transportation> searchTransport(String keyword) {
		Cursor cursor = null;
		ArrayList<Transportation> arrResult = new ArrayList<Transportation>();

		try {
			dbHelper = connectDB();
			database = dbHelper.getReadableDatabase();
			String queryTransportation = "SELECT Transport.[Id] , Transport.[Name] , Transport.[IconPath] , Transport.[PhoneNumber] , TransportCategory.[TransportName] FROM Transport "
					+ "LEFT JOIN TransportCategory ON Transport.[TransportId] = TransportCategory.[Id]  "
					+ "WHERE Transport.[Name] LIKE '%"
					+ keyword
					+ "%' OR Transport.[FirstLeg] LIKE '%"
					+ keyword
					+ "%' OR Transport.[SecondLeg] LIKE '%" + keyword + "%'";

			cursor = database.rawQuery(queryTransportation, null);
			if (cursor != null) {
				if (cursor.moveToFirst()) {
					do {

						Transportation transportation = new Transportation();
						transportation.setId(cursor.getInt(cursor
								.getColumnIndex("Id")));
						transportation.setName(cursor.getString(cursor
								.getColumnIndex("Name")));
						transportation.setIconPath(cursor.getString(cursor
								.getColumnIndex("IconPath")));
						transportation.setPhoneNumber(cursor.getString(cursor
								.getColumnIndex("PhoneNumber")));
						transportation.setCategory(cursor.getString(cursor
								.getColumnIndex("TransportName")));

						arrResult.add(transportation);
					} while (cursor.moveToNext());
				}
			}
		} catch (Exception e) {
			Log.v("Can't query DB searchTransport : ", e.toString());
		} finally {
			closeDB(database, dbHelper);
		}

		return arrResult;
	}

}
